package com.suxin.factory;

import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.ClassUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author Tang
 * @classname CodecConfigureFactory
 * @description [  ]
 * @date 2022/10/13 16:46
 */
public class CodecConfigureFactory {

    private static final String DEFAULT_CONFIGURERS_PATH = "CodecConfigure.properties";

    private static final Map<Class<?>, Class<?>> defaultCodecConfigurers = new HashMap<>();

    static {
        try {
            Properties props = PropertiesLoaderUtils.loadProperties(
                    new ClassPathResource(DEFAULT_CONFIGURERS_PATH,CodecConfigureFactory.class)
            );
            for (String ifcName : props.stringPropertyNames()) {
                String impName = props.getProperty(ifcName);
                Class<?> ifcClass = ClassUtils.forName(ifcName, CodecConfigureFactory.class.getClassLoader());
                Class<?> impClass = ClassUtils.forName(impName, CodecConfigureFactory.class.getClassLoader());
                defaultCodecConfigurers.put(ifcClass,impClass);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * create
     * @param tClass
     * @param <T>
     * @return
     */
    public static <T extends CodecConfigure> T create(Class<T> tClass) {
        Object instantiateClass = BeanUtils.instantiateClass(defaultCodecConfigurers.get(tClass));
        return (T)instantiateClass;
    }


}
